package com.daxia.bumall.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.daxia.bumall.basemodel.CoreUser;
import com.daxia.bumall.service.UserService;

@Component
public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
	
	@Autowired
	private UserService userService;
	
	@Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication au) throws IOException, ServletException {
		if (au != null && au.getPrincipal() != null && au.getPrincipal() instanceof CoreUser) {
		    CoreUser user = (CoreUser) au.getPrincipal();
			// request.getSession().setAttribute("isHead", user.getType() == ManagerType.Head.getValue());
		    request.getSession().setAttribute("isHead", false);
			// request.getSession().setAttribute("currentStoreId", user.getStore().getId());
		    request.getSession().setAttribute("currentStoreId", 0);
			// request.getSession().setAttribute("currentStoreName", user.getStoreName());
		    request.getSession().setAttribute("currentStoreName", "");
		    request.getSession().setAttribute("currentUser", user);
		    request.getSession().setAttribute("logined", true);
		    request.getSession().setAttribute("isAdmin", "admin".equalsIgnoreCase(user.getUsername()));
		    userService.updateLastLoginTime(user.getId());
		}
		String planId = (String) request.getSession().getAttribute("planId");
		if (StringUtils.isBlank(planId)) {
			super.setDefaultTargetUrl("/");
		} else {
			super.setDefaultTargetUrl("/buy/fromPlan?planId=" + planId);
		}
		super.setAlwaysUseDefaultTargetUrl(true);

		super.onAuthenticationSuccess(request, response, au);
    }

}
